package com.ruoyi.project.weixin.controller;

import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Slf4j
@AllArgsConstructor
@RestController
public class WxAuthController {

    private final WxMpService wxService;
    private final ISysUserService userService;
    private final TokenService tokenService;

    /**
     * 授权登录成功后的回调，获取用户信息
     * @param code
     * @return
     */
    @RequestMapping(value = "/weixin/auth/userInfo")
    public AjaxResult userInfo(
        @RequestParam(name = "code", required = false) String code){
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = null;
        try {
            wxMpOAuth2AccessToken = this.wxService.oauth2getAccessToken(code);
            WxMpUser wxMpUser = wxService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
            wxMpOAuth2AccessToken = this.wxService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
            boolean valid = wxService.oauth2validateAccessToken(wxMpOAuth2AccessToken);
            //获取token里面的用户信息
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            SysUser userNew = loginUser.getUser();
            SysUser user = new SysUser();
            user.setUserId(userNew.getUserId());
            user.setAvatar(wxMpUser.getHeadImgUrl());
//            user.setWxOpenId(wxMpUser.getOpenId());
//            userService.updateUserWxInfo(user);
            //刷新token里面用户的wxOpenId和头像
//            userNew.setWxOpenId(user.getWxOpenId());
            userNew.setAvatar(user.getAvatar());
            loginUser.setUser(userNew);
            tokenService.refreshToken(loginUser);
            this.log.info("auth2--用户信息：{},验证OAuth2AccessToken是否有效：{}",wxMpUser.toString(),valid);
            return AjaxResult.success(loginUser);
        } catch (Exception e) {
            e.printStackTrace();
            this.log.info("授权失败：{}", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 授权登录请求
     * @return
     */
    @RequestMapping(value = "/weixin/auth/authLogin",method = RequestMethod.GET)
    public AjaxResult authLogin(){
        String url = "http://ww.xzvv.cn/pages/user/authLogin";
        //返回授权的url
        String authUrl = this.wxService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
        log.debug("authurl:{},"+authUrl);
        return AjaxResult.success("ok",authUrl);
    }
}
